<template>
  <div>
    <s-container @reset="handleQueryReset" @search="handleQuery" :loading="loading">

      <template #searchForm>
        <n-form ref="searchRef" :label-width="80" :model="searchForm.value" label-placement="left" inline>
          <n-form-item label="用户名" path="roleName" class="fi-w">
            <n-input v-model:value="searchForm.value.nickName" clearable @keyup.enter.native="handleQuery" />
          </n-form-item>
          <n-form-item label="最后登录时间" :label-width="120" path="loginDate" class="fi-w">
            <n-date-picker v-model:formatted-value="searchForm.value.loginDate" type="date" clearable
              format="yyyy-MM-dd" />
          </n-form-item>
        </n-form>
      </template>
      <template #btnBar>
        <s-bar-add-btn @click="handleAddClick" v-permission="['system:user:add']" />
        <s-bar-del-btn :disabled="!(checkRows && checkRows.length > 0)" :click="handleDeleteListPositive"
          v-permission="['system:user:remove']" />
        <n-popover trigger="hover" placement="bottom" display-directive="show">
          <template #trigger>
            <n-button>Excel</n-button>
          </template>
          <n-space>
            <n-button color="#2ecc71" :on-click="handleExport">导出数据</n-button>
            <n-button color="#3498db" :on-click="handleExportTemplateUser">导出模版</n-button>
            <n-upload :custom-request="handleImportUser" :show-file-list="false" :max="1" ref="excelImportRef"
              accept=".xlsx,.xls">
              <n-button attr-type="button" color="#f39c12">模版导入</n-button>
            </n-upload>
          </n-space>
        </n-popover>
        <TableColumnSetting v-model:columns="columns" />
      </template>
      <template #toolBar>
      </template>
      <template #dataTable>
        <s-data-table :list="list" v-model:pageObj="pageObj" :columns="columns" :loading="loading"
          :checked-row-keys="checkRows.map(it => it.id)" @update:checked-row-keys="handleCheck"
          :row-class-name="rowClassName" :bordered="false" />
      </template>
    </s-container>

    <slef-form v-model:visible="showModal" :operate-type="editKey == null ? 'add' : 'edit'" :editKey="editKey"
      @submitted="handleSubmitted"></slef-form>
  </div>
</template>

<script setup lang='tsx'>
import { ref, onMounted, Ref } from 'vue';
import { DataTableColumns, NSpace, UploadCustomRequestOptions, UploadInst } from 'naive-ui';
import { usePageList } from '@/hooks';
import { isBusinessYse } from '@/utils/common'
import { fetchUserPage, fetchDeleteUser, fetchUserResetPw, fetchUpdateUserStatus, fetchUnbanUser, fetchExportUser, fetchExportTemplateUser, fetchImportUser } from '@/service/api/sys/user'
import PopconfirmBtn from "~/src/components/custom/popconfirm-btn.vue"
import SRowEditBtn from "~/src/components/custom/s-row-edit-btn.vue"
import SRowDelBtn from "~/src/components/custom/s-row-del-btn.vue"
import SContainer from "~/src/components/custom/s-container.vue"
import TablePopconfirmBtn from "~/src/components/custom/table-popconfirm-btn.vue"
import SDataTable from "~/src/components/custom/s-data-table.vue"
import SMoreTableBtn from "~/src/components/custom/s-more-table-btn.vue"
import { BusinessStatus } from "@/enum";
import slefForm from "./form.vue"
import { RowData } from 'naive-ui/es/data-table/src/interface';
import { saveAs } from 'file-saver';

interface DataSource extends SysAuth.UserInfo { }
interface SearchForm { nickName?: string | null, loginDate?: string }
const statusStrArr = ["启用", "禁用"]
const columnResizable: boolean = true;
const editKey = ref<Common.IdType | null>(null)
const excelImportRef = ref<UploadInst | null>()
const columns: Ref<DataTableColumns<DataSource>> = ref([
  {
    type: "selection"
  },
  {
    title: '登陆名',
    key: 'userName',
    align: 'center',
    resizable: columnResizable,
    width: 200,
  },
  {
    title: '用户名',
    key: 'nickName',
    align: 'center',
    resizable: columnResizable,
  },
  {
    title: '最后登陆时间',
    key: 'loginDate',
    align: 'center',
    ellipsis: {
      tooltip: true
    },
    sorter: true,
    resizable: columnResizable
  },
  {
    title: '状态',
    key: 'status',
    align: 'center',
    render(rowData: DataSource) {
      const status = rowData.status
      const statusStr = isBusinessYse(status) ? statusStrArr[0] : statusStrArr[1]
      const transStatusStr = isBusinessYse(status) ? statusStrArr[1] : statusStrArr[0]
      const btnType = isBusinessYse(status) ? "success" : "warning"
      return <>
        <PopconfirmBtn type={btnType} ghost="true" size="small" btnStr={statusStr} confirmText={`是否确定${transStatusStr}当前用户`}
          onPositiveClick={() => handleChangeRowStatus(rowData)}></PopconfirmBtn>
      </>
    },
    resizable: columnResizable,
  },
  {
    title: '创建者',
    key: 'createBy',
    align: 'center',
    resizable: columnResizable,
  },
  {
    title: '创建时间',
    key: 'createTime',
    align: 'center',
    ellipsis: {
      tooltip: true
    },
    sorter: true,
    resizable: columnResizable,
  },
  {
    title: "操作列",
    key: "",
    align: 'center',
    width: 200,
    fixed: 'right',
    render(rowData: DataSource) {
      return <>
        <NSpace justify="center">
          <SRowEditBtn onClick={() => handleEditClick(rowData)} v-permission={['system:user:edit']}></SRowEditBtn>
          <SRowDelBtn click={() => handleDeletePositive(rowData)} v-permission={['system:user:remove']}></SRowDelBtn>
          <SMoreTableBtn v-permission={['system:user:edit']}>
            <NSpace justify='space-around' >
              <TablePopconfirmBtn confirmText="是否确认重置当前用户密码" icon="system-uicons:reset" localIcon={false} tooltip="重置密码" type="warning" twidth={90} onPositiveClick={() => handleResetPassWord(rowData)} ></TablePopconfirmBtn>
              {
                rowData.ban == BusinessStatus.Yes ?
                  <TablePopconfirmBtn confirmText="是否确定解禁当前用户" icon="fluent:accessibility-48-filled" localIcon={false} tooltip="解禁用户" type="primary" twidth={90} onPositiveClick={() => handleUnbanUser(rowData.id!)} ></TablePopconfirmBtn>
                  : ''
              }
            </NSpace>
          </SMoreTableBtn>
        </NSpace>
      </>
    }
  }
]) as Ref<DataTableColumns<DataSource>>;
const checkRows = ref<DataSource[]>([]);
const {
  startLoading, endLoading,
  loading,
  searchForm,
  list,
  pageObj,
  getList,
  handleQueryReset,
  handleQuery
} = usePageList<DataSource>(
  initSearchFormData,
  fetchUserPage,
  beforeList,
  undefined
);


const showModal = ref(false);
function beforeList() {
  checkRows.value = [];
}
function initSearchFormData(): SearchForm {
  return { nickName: undefined, loginDate: undefined }
}

function handleCheck(keys: Array<string | number>, rows: DataSource[]) {
  checkRows.value = rows
}

async function handleDeleteListPositive() {
  await fetchDeleteUser(checkRows?.value.map(it => it.id!))
  getList()
  return true;
}
async function handleDeletePositive(row: DataSource): Promise<boolean> {
  if (!row || !row.id) {
    window.$message?.error("数据id异常,请刷新后重试")
    return false
  }
  await fetchDeleteUser([row.id])
  getList()
  return true
}
async function handleChangeRowStatus(row: DataSource) {
  const updateStatus = row.status == BusinessStatus.Yes ? BusinessStatus.No : BusinessStatus.Yes
  const { error } = await fetchUpdateUserStatus(row.id!, updateStatus)

  if (!error)
    window.$message?.success("操作成功")
  getList()
}


async function handleEditClick(row: DataSource) {
  if (!row || !row.id) {
    window.$message?.error("当前行数据异常,请刷新后重试")
    return;
  }
  editKey.value = row.id
  showModal.value = true;

}


function handleAddClick() {
  showModal.value = true;
}
function handleSubmitted() {
  editKey.value = null
  getList()
}
async function handleResetPassWord(row: DataSource) {
  const { error } = await fetchUserResetPw(row.id!)
  if (!error) {
    window.$message?.success("重置成功")
    getList()
  }
}
function rowClassName(row: RowData): string {
  if (row.ban == BusinessStatus.Yes) {
    return 'ban-row'
  }
  return ''
}
async function handleUnbanUser(id: Common.IdType) {
  const { error } = await fetchUnbanUser(id)
  if (!error) {
    window.$message?.success("操作成功")
  }
  getList()
}

async function handleExport() {
  startLoading()
  try {
    const { data } = await fetchExportUser(searchForm.value)
    const blob = new Blob([data!], { type: 'application/vnd.ms-excel' })
    saveAs(blob, "系统用户.xlsx")
  } finally {
    endLoading()
  }



}

async function handleExportTemplateUser() {
  startLoading()
  try {
    const { data } = await fetchExportTemplateUser()
    const blob = new Blob([data!], { type: 'application/vnd.ms-excel' })
    saveAs(blob, "系统用户模版.xlsx")
  } finally {
    endLoading()
  }

}

async function handleImportUser({ file, headers, withCredentials, action, onFinish, onError, onProgress }: UploadCustomRequestOptions) {
  onProgress = () => {
    startLoading()
  }
  onError = () => {
    endLoading()
  }
  onFinish = () => {
    endLoading()
  }
  const formData = new FormData()
  formData.append("file", file.file as File)
  const { error } = await fetchImportUser(formData)
  if (!error) {
    window.$message?.success("操作成功")
  } else {
    window.$message?.error(error.message)
  }
  excelImportRef.value?.clear()
  getList();

}

onMounted(() => {
  getList()
})
</script>

<style>
.ban-row>.n-data-table-td {
  background-color: rgba(0, 0, 0, 0.09) !important;
}
</style>
